package com.xl.yygh.msm.controller;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xl.yygh.common.result.Result;
import com.xl.yygh.msm.service.MsmService;
import com.xl.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author XiangLiang
 * @date 2023/11/1 17:33
 * @description
 */
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    @Resource
    private MsmService msmService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送手机验证码
     * @param phone 手机号
     * @return 验证码发送结果
     */
    @ApiOperation("发送手机验证码")
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        // 从redis获取验证码，如果获取获取到，返回ok
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.keys("*");
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        // 如果从redis获取不到，
        // 生成验证码，
        code = RandomUtil.getSixBitRandom();
        // 调用service方法，通过整合短信服务进行发送
        boolean isSend = msmService.send(phone, code);
        if (isSend) {
            // key 手机号  value 验证码
            // 验证码放入redis，过期时间两分钟
            redisTemplate.opsForValue().set(phone, code, 2L, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail().message("发送短信失败");
        }
    }

}
